package main.com.votes.controller;


import main.com.votes.dao.UserDao;
import main.com.votes.model.User;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    UserDao userDao = new UserDao();


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // Perform user authentication (here using a simple hardcoded example)

        User user = userDao.getUserByUsername(username);
        if (user != null) {
            if (password.equals(user.getPassword())) {
                // Successful login
                request.getSession().setAttribute("username", username);
                request.getSession().setAttribute("userId", user.getId());
//                response.sendRedirect("admin/index.jsp");
                request.getRequestDispatcher("/articleListServlet").forward(request, response);
            }else {
                // Failed login
                request.setAttribute("msg", "账号或者密码错误！");
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
        }else{
            // Failed login
            request.setAttribute("msg", "账号不存在");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }


}
